package io.sdl.controller;

import io.sdl.common.sys.entity.SdlDoctorsEntity;
import io.sdl.common.sys.service.SdlDoctorsService;
import io.sdl.common.utils.ConvertUtils;
import io.sdl.common.utils.Result;
import io.sdl.common.constant.UrlConstants;
import io.sdl.dto.UpdateUserDTO;
import io.sdl.entity.TokenEntity;
import io.sdl.entity.UserEntity;
import io.sdl.service.TokenService;
import io.sdl.service.UserService;
import io.sdl.utils.StringHandlsUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * 用户信息接口相关
 *
 * @authorDc 1211734836@qq.com
 */
@RestController
@RequestMapping("/api")
@Tag(name = "用户信息接口相关")
public class ApiUserController {

	@Autowired
	private TokenService tokenService;

	@Autowired
	private UserService userService;

	@Autowired
	private SdlDoctorsService sdlDoctorsService;

	@PostMapping("userInfo")
	@Operation(summary = "获取用户信息")
	private Result<UpdateUserDTO> queryUser(@RequestBody String token) {

		// 判断并删除开头的 "
		if (token.startsWith("\"")) {
			token = token.substring(1);
		}

		// 判断并删除结尾的 "
		if (token.endsWith("\"")) {
			token = token.substring(0, token.length() - 1);
		}
		//token续期
		TokenEntity tokenEntity = tokenService.getByToken(token);
		//获取用户信息
		UserEntity user = userService.getUserByUserId(tokenEntity.getUserId());

		user.setAvatarUrl(UrlConstants.getProductionUrl() + user.getAvatarUrl());
		UpdateUserDTO updateUserDTO = ConvertUtils.sourceToTarget(user, UpdateUserDTO.class);
		SdlDoctorsEntity byPhone = sdlDoctorsService.findByPhone(user.getMobile());
		if (byPhone != null) {
			updateUserDTO.setTechnologyType(byPhone.getTechnologyType());
			updateUserDTO.setTitle(byPhone.getTitle());
			updateUserDTO.setHospital(byPhone.getHospital());
			updateUserDTO.setImagesList(StringHandlsUtils.splitImageUrlsToList(byPhone.getCertificates()));
			updateUserDTO.setExperience(byPhone.getExperience());
			updateUserDTO.setDoctorsProevalution(byPhone.getDoctorsProevalution());
			updateUserDTO.setDoctorsSelfIntroduction(byPhone.getDoctorsSelfIntroduction());

			updateUserDTO.setPassWord(user.getPassword() == null ? "pswErrorFalse" : user.getPassword());
		}
		return new Result<UpdateUserDTO>().ok(updateUserDTO);
	}


	@PostMapping("user/update")
	@Operation(summary = "修改用户信息")
	private Result saveUserInfo(@RequestBody UpdateUserDTO user) {

		SdlDoctorsEntity sdlDoctorsEntity = new SdlDoctorsEntity();
		//当角色为专家时
		if (user.getUserRole().equals("doctor")) {
			sdlDoctorsEntity = sdlDoctorsService.findByPhone(user.getMobile());


			sdlDoctorsEntity.setUserPhone(user.getMobile());
			sdlDoctorsEntity.setTechnologyType(user.getTechnologyType());
			sdlDoctorsEntity.setDoctorsSelfIntroduction(user.getDoctorsSelfIntroduction());
			sdlDoctorsEntity.setExperience(user.getExperience());
			sdlDoctorsEntity.setTitle(user.getTitle());
			sdlDoctorsEntity.setHospital(user.getHospital());
			sdlDoctorsEntity.setCertificates((user.getCertificates() != null && !user.getCertificates().equals("")) ? user.getCertificates() : null);

			//专业评价


			//资格证书保存

			if (sdlDoctorsEntity != null) {

				sdlDoctorsService.updateById(sdlDoctorsEntity);
			} else {
				sdlDoctorsEntity.setIsDel(1);
				//保存专家信息
				sdlDoctorsService.insert(sdlDoctorsEntity);
			}

		}
		userService.saveUserInfo(user);
		return new Result().ok(user.getId());
	}


	@PostMapping("upload/avatar")
	@Operation(summary = "图片上传")
	public Result uploadPatient(@RequestParam(value = "file", required = false) MultipartFile file, Long id, String isAvatar) {
		try {

			if (isAvatar.equals("Avatar")) {
				// 1. 保存文件并返回地址
				userService.saveUploadedFile(file, id);
			}

			if (isAvatar.equals("certificates")) {
				UserEntity userEntity = userService.selectById(id);
				SdlDoctorsEntity byPhone = sdlDoctorsService.findByPhone(userEntity.getMobile());
				sdlDoctorsService.saveUploadedFile(file, byPhone.getDoctorsId());
			}
			UserEntity userEntity = userService.selectById(id);
			return new Result().ok(userEntity);
		} catch (Exception e) {
			return new Result().error(500, "文件上传失败: " + e.getMessage());

		}
	}


	@PostMapping("user/check-mobile")
	@Operation(summary = "手机号注册校验")
	private Result<Boolean> checkMobile(@RequestBody UpdateUserDTO dto) {
		Boolean b = false;
		//获取当前用户的手机号
		TokenEntity byToken = tokenService.getByToken(dto.getToken());

		UserEntity user = userService.getUserByUserId(byToken.getUserId());

		//与用户输入的手机号做对比
		if (!dto.getMobile().equals(user.getMobile())) {

			UserEntity byMobile = userService.getByMobile(dto.getMobile());
			//判断手机号有没有被注册
			if (byMobile != null) {
				b = true;
			}
		}

		return new Result().ok(b);
	}

	@PostMapping("getUserInfo")
	@Operation(summary = "根据id获取用户信息")
	private Result<UpdateUserDTO> queryUserInfo(@RequestBody Long id) {

		//获取用户信息
		UserEntity user = userService.getUserByUserId(id);

		user.setAvatarUrl(UrlConstants.getProductionUrl() + user.getAvatarUrl());
		UpdateUserDTO updateUserDTO = ConvertUtils.sourceToTarget(user, UpdateUserDTO.class);
		SdlDoctorsEntity byPhone = sdlDoctorsService.findByPhone(user.getMobile());
		if (byPhone != null) {
			updateUserDTO.setTechnologyType(byPhone.getTechnologyType());
			updateUserDTO.setTitle(byPhone.getTitle());
			updateUserDTO.setHospital(byPhone.getHospital());
			updateUserDTO.setImagesList(StringHandlsUtils.splitImageUrlsToList(byPhone.getCertificates()));
			updateUserDTO.setExperience(byPhone.getExperience());
			updateUserDTO.setDoctorsProevalution(byPhone.getDoctorsProevalution());
			updateUserDTO.setDoctorsSelfIntroduction(byPhone.getDoctorsSelfIntroduction());
		}
		return new Result<UpdateUserDTO>().ok(updateUserDTO);
	}


	@PostMapping("/user/checkPasswordStatus")
	@Operation(summary = "根据用户token检查密码状态")
	private Result checkPasswordStatus(@RequestBody String token) {

		TokenEntity byToken = tokenService.getByToken(token);

		UserEntity userEntity = userService.getUserByUserId(byToken.getUserId());
		if (userEntity.getPassword() == null) {
			userEntity.setPassword("pswErrorFalse");
			return new Result().ok(userEntity);
		} else {
			return new Result().ok(userEntity);
		}

	}

	@PostMapping("/user/updatePassword")
	@Operation(summary = "修改密码")
	private Result updatePassword(@RequestBody Map<String, String> params) {

		TokenEntity byToken = tokenService.getByToken(params.get("token"));
		String p = params.get("oldPassword");
		String n = params.get("newPassword");
		if (p.equals(n)) {
			return new Result().error(501, "新密码不得与原密码一样!");
		}
		UserEntity userEntity = userService.getUserByUserId(byToken.getUserId());
		//检查原密码是否一致
		String oldPwd = md5(p);

		if (!oldPwd.equals(userEntity.getPassword())) {
			return new Result().error(500, "原密码输入错误!");
		}
		String newPwd = md5(n);
		userEntity.setPassword(newPwd);

		userService.updateById(userEntity);
		return new Result().ok("密码修改成功!");
	}


	@PostMapping("/user/setPassword")
	@Operation(summary = "设置密码")
	private Result setPassword(@RequestBody Map<String, String> params) {
		TokenEntity byToken = tokenService.getByToken(params.get("token"));

		UserEntity user = userService.getUserByUserId(byToken.getUserId());
		String n = params.get("newPassword");
		String newPwd = md5(n);
		user.setPassword(newPwd);
		userService.updateById(user);
		return new Result().ok("密码修改成功!");
	}


	private String md5(String p) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");

			md.update(p.getBytes());

			String pwd = new BigInteger(1, md.digest()).toString(16);

			return pwd;
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}


	}
}
